package com.wan.config.security;

import com.wan.service.system.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity//开启security
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启全局security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 解决 Spring Boot 出现 in a frame because it set 'X-Frame-Options' to 'DENY'
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                //允许的url放在这下面
                .mvcMatchers("/caipu/test","/management/caipu/edit/food").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                //设置登录页
                .formLogin().loginPage("/user/login")
                //登录成功跳转的页面
                .defaultSuccessUrl("/caipu/index").permitAll()
                .failureUrl("/user/login/error")
                //.successForwardUrl("/caipu/index")
                //.failureForwardUrl("/user/login")
                // 自定义登陆用户名和密码参数，默认为username和password
//                .usernameParameter("username")
//                .passwordParameter("password")
                .and().logout().permitAll()
                //session管理
                .and().sessionManagement().invalidSessionUrl("/user/login/error");
        // 关闭CSRF跨域
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置拦截忽略文件夹，可以对静态资源放行
        web.ignoring().antMatchers("/static/**", "/js/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}
